/*
 * industryShare.js
 * 行业共享
 */
;
(function (call) {
	var main = {
		baseUrl: CafeJS.CXT,
		mapId: "tjMap",
		playList: null,
		datepicker: null,
		legendpicker: null,
		latestTime: null,
		selectElements:[],
		router: {
			getIndustryShareStatData: '/industryshare/InSharing/queryMusicInfo',
			getLatestTime: 'zhfx/station/skTime',
			productcfg: "/business/common/json/product.json",
            dataCfg:"/business/common/json/industryShare.json"
		},
		init: function () {
            var that = this;
            that.initView();
            that.bindEvt();
			
		},
		initView: function () {
			var that = this;
			that.getLatestTime();
			that.initDatePicker();
			$.getJSON(that.router.productcfg, function (cfg) {
				that.initProductList(cfg);
			})
		},
		// 获取自动站最新实况时间
		getLatestTime: function () {
			var that = this;
			$.ajax({
				url: this.router.getLatestTime,
				type: 'GET',
				dataType: 'json',
				async: false
			}).done(function (res) {
				if (res.isSuccess)
					that.latestTime = res.data;
			})
		},
		// 初始化产品列表
		initProductList: function (cfg) {
			var that = this;
			var params = {
				container: '.product-content.industyrshare',
				data: cfg.industryShare,
				eleClick: function (ele, oldEle, selected) {
					var ptype = ele.type; //当前要素的类型
					var name = ele.ele_name;
                    debugger    
					that.clearLayer([ptype]);
					var pro = {
						name: '行业共享_' + ele.categoryName+"_"+name,
						time: that.calcStartTime(ele),
						bussitype: 'industryShare',
						ele: ele,
						isGrid: false,
						isSK: true
					}
                    
					if (selected) {
						// 增加产品图层
						that.addLayerManage(pro);
						that.queryEleData(ele, pro.time);
					} else {
						CafeJS.layerManage.removeLayer(pro); // 删除当前要素的图层
					}
				},
				
			};
            debugger
			CafeJS.analysis(params);
			if (new Date(that.datepicker.getVal()).getMinutes() !== 0) {
				that.preventEventByMinute(true);
			} else {
				that.preventEventByMinute(false);
			}
		},
		// 初始化时间控件
		initDatePicker: function () {
			var _this = this;
			this.datepicker = CafeJS.Datepicker({
				appendTo: "#datepicker-industryShare",
				curDate: _this.latestTime,
				type: 9,
				timeInterval: 5,
				ttimeInterval: 1,
				autoPush: true,
				call: function (val) {
					$(".ranking-head span").empty().text(new Date(val).format('yyyyMMdd hhmm'));
					if (new Date(_this.datepicker.getVal()).getMinutes() !== 0) {
						_this.preventEventByMinute(true);
					} else {
						_this.preventEventByMinute(false);
                    }
                    _this.queryMultiEleData();
				},
				updateDateCall: function () {
					if (new Date(_this.datepicker.getVal()).getMinutes() !== 0) {
						_this.preventEventByMinute(true);
					} else {
						_this.preventEventByMinute(false);
					}
				}
			});
			$("#datepicker-industryShare").show();
		},
		//当分为00时，元素不能点击，置灰
		preventEventByMinute: function (flag) {
			$(".product-list li").each(function (index) {
				var $obj = $(this);
				var eleId = $obj.data("pro").ele_id;
				if (eleId === "Snow_Depth") {
					if (flag) {
                        if ($obj.hasClass("active")) {
                            $obj.click();
                        }
						$obj.addClass("preventEventLi");
						$obj.children().addClass("preventEvent");
						$obj.attr("title", "整点统计数据");
					} else {
						$obj.removeClass("preventEventLi");
						$obj.children().removeClass("preventEvent");
						$obj.attr("title", "");
					}
				}
			})
		},
		// 初始化播放列表
		initPlayList: function (pro) {
			var that = this;
			var startTime = pro.time;

			var layers = this.getModels(pro.ele);
			var interval = pro.ele.interval || 5;
			this.playList = CafeJS.Timeline3({
				appendTo: "#a-m-timeline",
				curDate: startTime,
				type: 1,
				pro: pro,
				dateOpt: {
					dateFmt: 'yyyy-MM-dd hh:mm',
					timeInterval: interval,
					customHm: []
				},
				timeInterval: interval,
				layers: layers,
				gisId: that.mapId,
				call: function (pro) {
					CafeJS.layerManage.updateLayer(pro);
					var ele = pro.ele;
                    that.queryEleData(ele, pro.time);
				},
				getPlayData: function (pro, timeArr) {
				}
			});
		},
		// 查询已选择要素
		queryMultiEleData: function () {
			var that = this;
			var pro, time;
			$(".industyrshare .product-list li.active").each(function (i, ele) {
				pro = $(ele).data('pro');
				time = that.calcStartTime(pro);
				CafeJS.layerManage.updateLayerTime(time, 'industryShare', null, pro.ele_id);
				that.queryEleData(pro, time);
			});
		},
		// 查询要素数据
		queryEleData: function (ele, time) {
			var that = this;
			var ptype = ele.type;
			that.clearLayer([ptype]);
			that.queryAwsStatData(ele, time);
		},
		// 查询站点数据
		queryAwsStatData: function (ele, time) {
			var that = this;
            debugger
			time = new Date(time).format('yyyy-MM-dd hh:mm:ss');
			var element = ele.ele_id;
            $.ajax({
				url: that.router.getIndustryShareStatData,
				data: {
                    dataCode:ele.category,
                    stime:new Date(time).format('yyyyMMddhhmmss')
                },
				type: "GET",
				dataType: 'json',
				success: function (res) {
                    debugger
                    if(res.returnCode != "0" && res.returnCode != "-1"){
                        alert("查询失败");
                        return; 
                    }
                    let data = res.DS;
                    if (!data || data.length === 0){
						alert("该时间点"+ele.ele_name+"没有数据");
						return
					};
					var eleType = ele.type;
					var statTypes = [0], dataArr = {};
					statTypes.forEach(function (type, index) {
						dataArr[type] = {};
					})
					data.forEach(function (station, index) {
                        station.stationType=0;
                        station.lat=station.Lat;
                        station.lon=station.Lon;
                        station.stationId=station.Station_Id_C;
						if (!station.lon) return;
                        
						station.lat=Number(station.lat);
                        station.lon=Number(station.lon);
                        station.val=station[element];
                        if(element == "WIN_S"){
                            station.val2=Number(station["WIN_D"]);
                        }
                        if(element == "WIN_S_Inst_Max"){
                            station.val2=Number(station["WIN_D_Inst_Max"]);
                        }
                        if (station.val>999990) return;
                        if (station.lon>999990) return;
                        if (station.lon>999990) return;
						if (eleType == 'TP'){
							if (station.val == 0){
								return;
							};	
						};
                        station.val = parseFloat(Number(station.val).toFixed(1))
						station.options = {
							labelStyle: $.extend(false, { fillStyle: that.getLabelObj(eleType).scolor, size: 14, textAlign: "center" }, that.getLabelObj(eleType)),
							bgStyle: { fillStyle: "rgba(0,0,0,0)", strokeStyle: "rgba(0,0,0,0)", radius: 3 }
						}
						if (dataArr[station.stationType][eleType]) {
							dataArr[station.stationType][eleType].push(station)
						} else {
							dataArr[station.stationType][eleType] = [];
							dataArr[station.stationType][eleType].push(station)
						}
					})
					var statArr = [];
					statTypes.forEach(function (type, index) {
						if ($.isEmptyObject(dataArr[type])) {
							delete dataArr[type];
						} else {
							statArr.push(type);
						}
					})
					if (statArr.length === 0) {
						return;
					}
					var dataObj = {
						dataArr: dataArr,
						eleTypes: [eleType],
						statTypes: statArr
					}
                    debugger
					GIS.Station.showElements(that.mapId, dataObj, that.getStatStyleObj(), {}, null, null, { 'cx': true });
                }
            })	
		},
		// 绘制格点色斑图
		drawGridRawMap: function (data, ele) {
			var that = this;
			var typeArr = this.getModels(ele);
            var colorObj = CafeJS.Legentconfig().cfg()[ele.color_id] || {};
            if (ele.models == 'isoline') {
                gridUtil.createIsoline(data, typeArr[0].id, colorObj.levels, GLMap.geometryData.areaconfig.Haihe.rings);
            } else {
				// 显示色斑和数值
				colorObj.cutFlag = true;
				colorObj.areaCode = 'Haihe';
                GIS.GridShow.showGrid(this.mapId, typeArr, data, {}, colorObj);
			}
			var min = ele.type == 'TP'?0.1:null;
			CafeJS.legentPicker.updateLegentRange(typeArr,that.mapId,min);
		},
		// 增加产品图层
		addLayerManage: function (pro) {
            debugger
			var that = this;
			if (CafeJS.layerManage) {
				CafeJS.layerManage.addLayer(pro);
			} else {
				CafeJS.layerManage = CafeJS.LayerManage({
					appendTo: "#c-b-layermanage",
					mapId: that.mapId,
					proInfo: pro,
					call: function (pro) {
						CafeJS[pro.bussitype].initPlayList(pro);
					},
					more: function (pro) {
						CafeJS[pro.bussitype].stationView(pro);
					},
					close: function (pro) {
						CafeJS[pro.bussitype].delLayer(pro);
					}
				})
			}
		},
		// 根据时间间隔获取开始时间
		calcStartTime: function (ele) {
			var time = new Date(this.datepicker.getVal());
			switch (ele.interval) {
				case 10:
					time.setMinutes(Math.floor(time.getMinutes() / 10) * 10);
					break;
				case 60:
					time.setMinutes(0);
					break;
			}
			return time.format('yyyy-MM-dd hh:mm');
		},
		// 删除图层后取消要素选择
		delLayer: function (pro) {
			var eleid = pro.ele.ele_id;
			var ptype = pro.ele.type;
			if (pro.isGrid) {
				var $grid = $(".industyrshare .product-list i.active");
				if ($grid.parent().data('eleid') == eleid)
					$grid.click();
				return false;
			}
			$(".industyrshare .product-list li.active").each(function () {
				if ($(this).data('eleid') == eleid) {
					$(this).click();
					return false;
				}
			})
		},
		// 清除单要素GIS图层
		clearLayer: function (eleid) {
			GIS.Station.eleShowControl(this.mapId, [0, 1, 2, 3, 4, 5], eleid, "delete");
		},
		// 清除格点GIS图层
		clearGridLayer: function (eleid) {
			var layerIds = [];
			GLMap.layerIds.forEach(function (layerId) {
				if (layerId.indexOf('industryShare-layer') != -1 && layerId.lastIndexOf(eleid) != -1) {
					layerIds.push(layerId);
				}
			})
			GIS.LayerControll.deleteLayer(this.mapId, layerIds);
		},
		// 获取站点GIS图层id
		getStatLayerIds: function () {
			var layerIds = [];
			$(".industryShare .product-list li.active").each(function () {
				var eleid = $(this).data("pro").type;
				[0, 1, 2, 3, 4, 5].forEach(function (st) {
					layerIds.push(eleid + st + "Stat");
				});
			});
			return layerIds;
		},
		// 获取要素样式
		getModels: function (ele) {
			var models = [];
			$.each(ele.models.split(","), function (i, m) {
				var layerId = "industryShare-layer-" + m + "-" + ele.ele_id;
				models.push({
					type: m,
					visible: true,
					uv: false,
					wd: (ele.type == 'WIND' || ele.type == 'WIND2') ? true : false,
					id: layerId
				});
			});
			return models;
		},
		bindEvt: function () {
		},
		// 获取站点类型样式
		getStatStyleObj: function () {
			var styleObj = {
				minLevel: 0,
				size: 8,
				font: { color: { a: 1, r: 1, g: 0, b: 0 }, xOffset: 0, yOffset: 20, size: '16px', length: 26, width: 8 }
			};
			return {
				//基本站
				0: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 }),
			};
		},
		// 获取要素样式
		getLabelObj: function (eleType) {
			var labelObj = {
				/**"TEM": { color: { R: 233, G: 40, B: 70, A: 1 }, scolor: "rgb(233,40,70)", lineWidth : 1, offx : -20, offy : 0, size : 16},
				"TP": { color: { R: 50, G: 202, B: 30, A: 1 }, scolor: "rgb(50,202,30)", lineWidth : 1, offx : 20, offy : 0, size : 16},
				"RH": {color : {R : 101, G : 83, B : 215, A : 1}, scolor: "rgb(101,83,215)", lineWidth : 1, offx : 0, offy : -20, size : 16},*/
                "WIND": { xOffset: 0, yOffset: 0, scolor: "rgb(0,0,0)" },
				"VIS": { xOffset: 35, yOffset: 20, scolor: "rgb(70,135,33)" },
				"TMP": { xOffset: 0, yOffset: 20, scolor: "rgb(200,30,70)" },
				"TP": { xOffset: 35, yOffset: 0, scolor: "rgb(74,140,84)" },
				"RH": { xOffset: 0, yOffset: -20, scolor: "rgb(101,83,215)" },
				"SP": { xOffset: 35, yOffset: -20, scolor: "rgb(157,78,231)" },
                "WIND2": { xOffset: 35, yOffset: -20, scolor: "rgb(157,78,231)" }
			}
			return labelObj[eleType];
		}
	};
	if (typeof call === 'function') {
		CafeJS.industryShare = main;
		call(main);
	}

})(function (main) {
	CafeJS.models(['datepicker', 'legentpicker', 'legentconfig', 'ajax', 'squarelegend', 'timeLine3'], function () {
		main.init();
	});
});
